package com.oneraku.service.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.oneraku.service.exceptions.InfoException;
import com.oneraku.service.service.IAliyunService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: hui.ren@huberbuy.com
 * @Date: 2019/9/23 14:40
 */
@Service
public class AliyunServiceImpl implements IAliyunService {
    @Override
    public Object getSts() {
        String endpoint = "sts.aliyuncs.com";
        String accessKeyId = "LTAI4FeD6wRP66KUn8uq2z2N";
        String accessKeySecret = "qOZdAFWPfbIkEH5Ngo6whj77JpUtjt";
        String roleArn = "acs:ram::1059299916294988:role/aliyunosstokengeneratorrole";
        String roleSessionName = "AliyunOSSTokenGeneratorRole";
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:*\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:*\" \n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        try {
            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setSysEndpoint(endpoint);
            request.setSysMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy); // Optional
            final AssumeRoleResponse response = client.getAcsResponse(request);
            JSONObject ret = new JSONObject();
            ret.put("expiration",response.getCredentials().getExpiration());
            ret.put("accessKeyId",response.getCredentials().getAccessKeyId());
            ret.put("accessKeySecret",response.getCredentials().getAccessKeySecret());
            ret.put("securityToken",response.getCredentials().getSecurityToken());
            return ret;
        } catch (ClientException e) {
            throw new InfoException(e.getErrMsg());
        }
    }

    @Override
    public Object getSign() {
        String accessId = "LTAI4FeD6wRP66KUn8uq2z2N"; // 请填写您的AccessKeyId。
        String accessKey = "qOZdAFWPfbIkEH5Ngo6whj77JpUtjt"; // 请填写您的AccessKeySecret。
        String endpoint = "oss-cn-shanghai.aliyuncs.com"; // 请填写您的 endpoint。
        String bucket = "oneraku-resource"; // 请填写您的 bucketname 。
        String host = "https://" + bucket + "." + endpoint;
        String dir = "upload/";
        OSSClient client = new OSSClient(endpoint, accessId, accessKey);
        JSONObject respMap = new JSONObject();
        try{
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return respMap;
        }
    }
}
